package com.ly.mp.dal.comm.jdbc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReadWriteDataSourceDecision {
    private static final Logger log = LoggerFactory.getLogger(ReadWriteDataSourceDecision.class);
    private static final String PREFIXED_DS = "default";
    private static final ThreadLocal<String> holder = new ThreadLocal<>();
    
    private ReadWriteDataSourceDecision() {
    }

    public static void markWrite(String prefixed) {
        String prefixedDs = prefixed == null ? PREFIXED_DS : prefixed;
        String dsKey = prefixedDs + "_" + ReadWriteDataSourceDecision.DataSourceType.writeDBKey;
        holder.set(dsKey);
        log.info("当前设置的数据源key:{}", dsKey);
    }

    public static void markRead(String prefixed) {
        String prefixedDs = prefixed == null ? PREFIXED_DS : prefixed;
        holder.set(prefixedDs + "_" + ReadWriteDataSourceDecision.DataSourceType.readDBKey);
    }
    
    public static void reset() {
        holder.remove();
    }

    public static boolean isChoiceNone() {
        return null == holder.get();
    }

    public static boolean isChoiceWrite() {
        return holder.get() != null && holder.get().endsWith(ReadWriteDataSourceDecision.DataSourceType.writeDBKey.name());
    }

    public static boolean isChoiceRead() {
        return holder.get() != null && holder.get().endsWith(ReadWriteDataSourceDecision.DataSourceType.readDBKey.name());
    }

    public static String getDsKey() {
        return holder.get();
    }

    public enum DataSourceType {
        writeDBKey, readDBKey;
    }
}